<?php
/**
 * Controller_Ajax_Order
 *
 * Класс Controller_Ajax_Order отвечает за обработку запросов связанных с заказами
 */
class Controller_Ajax_Order extends Controller_Ajax {

	/**
	 * (non-PHPdoc)
	 *
	 */
	public function actionSwitch() {
	  Service_Debug::setDebug();
		switch ($this->arrRequest[2]) {
			case 'fast_add':
				if(User_User::getUserType() != 'master') $this->actionAdd();
				else $this->setError(404);
				break;
			case 'response':
				if(User_User::getUserType() == 'master' || SimpleAdministration::isAdmin()) $this->addResponse();
				else $this->setError(404);
				break;
			case 'check_user':
				$this->checkUser();
				break;
			default: $this->setError(404);
 		}
	}

	
	/**
	 * Добавление заказа
	 *
	 */
	public function actionAdd () {
		Service_Debug::setDebug();
		$objSession = User_Session::instance();
		$first_name = isset($_POST['first_name']) ? Service_Escape::absolutelyEscapeString($_POST['first_name']) : '';
		$last_name = isset($_POST['last_name']) ? Service_Escape::absolutelyEscapeString($_POST['last_name']) : '';
		$eMail = isset($_POST['e_mail']) ? Service_Escape::absolutelyEscapeString($_POST['e_mail']) : '';
		$pass = isset($_POST['pass']) ? Service_Escape::absolutelyEscapeString($_POST['pass']) : '';
		$passConfirm = isset($_POST['pass_confirmation']) ? Service_Escape::absolutelyEscapeString($_POST['pass_confirmation']) : '';
		$order_name = isset($_POST['order_name']) ? Service_Escape::absolutelyEscapeString($_POST['order_name']) : '';
		$description = isset($_POST['description']) ? Service_Escape::absolutelyEscapeString($_POST['description']) : '';
		$city = isset($_POST['city']) ? Service_Escape::absolutelyEscapeString($_POST['city']) : '';
		$phone = isset($_POST['phone']) ? Service_Escape::absolutelyEscapeString($_POST['phone']) : '';
		$cost = isset($_POST['cost']) ? Service_Escape::absolutelyEscapeString($_POST['cost']) : '';
		$kaptcha = isset($_POST['kaptcha']) ? Service_Escape::absolutelyEscapeString($_POST['kaptcha']) : '';
		
		if (empty($order_name) || empty($description) || empty ($city) ) return $this->makeStandardError('Ошибка');
		
		if(!$objSession->isLoggedIn()) {
			if(User_User::isEMailExist($eMail)) return $this->makeStandardError('mailDublicated');
			$orderArray = array (
							'first_name' => $first_name,
							'last_name' => $last_name,
							'e_mail' => $eMail,
							'pass' => $pass,
							'pass_confirmation' => $passConfirm,
							'order_name' => $order_name,
							'description' => $description,
							'city' => $city,
							'phone' => $phone,
							'cost' => $cost,
							'kaptcha' => $kaptcha,
							'save' => 'Отправить'
							);
			$objSession = User_Session::instance();
			if($kaptcha != $objSession->__get('keystring')) return $this->makeStandardError('kaptchaError');
			}
		else $orderArray = array (
							'order_name' => $order_name,
							'description' => $description,
							'city' => $city,
							'phone' => $phone,
							'cost' => $cost
							);
		
		$objOrder = new Order();
		$objOrder->setFields($orderArray);
		
		if($objOrder->save()) {
			$this->arrReturn = array('result' => 'OK', 'orderId' => $objOrder->id);
		}
	}
	
	public function checkUser () {
		Service_Debug::setDebug();
		$objSessiion = User_Session::instance();
		if($objSessiion->isLoggedIn()) {
			if(User_User::getUserType() == 'customer') $this->arrReturn = array('userType' => 'true', 'login' => 'true' );
			else $this->arrReturn = array('userType' => 'false', 'login' => 'true' );
		}
		else $this->arrReturn = array('login' => 'false' );
	}
	
	/**
	 * Функция добавления нового отклика на заказ
	 *
	 */
	public function addResponse() {
		Service_Debug::setDebug();
		$objSession = User_Session::instance();
		
		$masterId = $objSession->getUserId();
		$orderId = isset($_POST['ID_order']) ? Service_Escape::absolutelyEscapeString($_POST['ID_order']) : '';
		$text = isset($_POST['text']) ? Service_Escape::absolutelyEscapeString($_POST['text']) : '';
		
		if (empty($orderId) || empty($text)) return $this->makeStandardError('Ошибка');
		
		$objOrder = new Order($orderId);
		if ($objOrder->id) { // Если существует заказ с переданным id
			// Если юзер залогинен, является мастером
			if($objSession->isLoggedIn() && User_User::getUser()->getField('user_type') == 'master') {
				$objOrederResponse = new OrderResponse();
				// Если текущей мастер уже откликался
				if($objOrederResponse->count("`ID_order`='" . $orderId . "' AND `ID_user`='" . $masterId . "'") != 0) return $this->makeStandardError('alredyExists');
				$arrayToSave = array (
								'ID_order' => $orderId,
								'ID_user' => $masterId,
								'text' => $text,
								'save' => 'Отправить'
								);
				$objOrederResponse->setFields($arrayToSave);
				if($objOrederResponse->save()) {
					$responsesCount = $objOrederResponse->count("`ID_order`='" . $orderId . "'");
					$this->arrReturn = array('result' => 'OK', 'responseCount' => $responsesCount);
				}
			}
		}
	}
}
?>